const ble = require('../../utils/ble');

function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(new Uint8Array(buffer), bit => ('00' + bit.toString(16)).slice(-2));
  return hexArr.join(' ');
}

Page({
  data: {
    name: '',
    deviceId: '',
    logs: [],
    hex: '',
    text: ''
  },

  onLoad(query) {
    this.setData({ name: decodeURIComponent(query.name || ''), deviceId: query.id || '' });
    ble.onNotify(({ value }) => {
      const hex = ab2hex(value);
      const now = new Date().toLocaleTimeString();
      this.setData({ logs: [`[${now}] ${hex}`, ...this.data.logs].slice(0, 200) });
    });
  },

  onUnload() {
    // 页面退出不强制断开，交给用户
  },

  onHexInput(e) { this.setData({ hex: e.detail.value }); },
  onTextInput(e) { this.setData({ text: e.detail.value }); },

  async sendHex() {
    try {
      await ble.writeHex(this.data.hex);
      wx.showToast({ title: '已发送', icon: 'success' });
    } catch (e) {
      wx.showToast({ title: '发送失败', icon: 'none' });
    }
  },

  async sendText() {
    try {
      await ble.writeText(this.data.text);
      wx.showToast({ title: '已发送', icon: 'success' });
    } catch (e) {
      wx.showToast({ title: '发送失败', icon: 'none' });
    }
  },

  async onDisconnect() {
    await ble.disconnect();
    wx.navigateBack();
  }
});


